import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:orginone/utils/log/log_util.dart';

import 'index.dart';

/// 记录路由的变化
class RouteObservers<R extends Route<dynamic>> extends RouteObserver<R> {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    var name = route.settings.name;
    RoutePages.addHistory(name);
    FocusManager.instance.primaryFocus?.unfocus();
    XLogUtil.d('didPush');
    XLogUtil.d('did ${RoutePages.history().toString()}');
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    RoutePages.removeHistory(route.settings.name);
    FocusManager.instance.primaryFocus?.unfocus();

    XLogUtil.d('didPop');
    XLogUtil.d('did ${RoutePages.history().toString()}');
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute != null) {
      var index = RoutePages.history().indexWhere((element) {
        return element == oldRoute?.settings.name;
      });
      var name = newRoute.settings.name ?? '';
      if (index > 0) {
        RoutePages.history()[index] = name;
      } else {
        RoutePages.addHistory(name);
      }
    }
    XLogUtil.d('didReplace');
    XLogUtil.d('did ${RoutePages.history.toString()}');
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    RoutePages.removeHistory(route.settings.name);
    XLogUtil.d('didRemove');
    XLogUtil.d('did ${jsonEncode(RoutePages.history())}');
  }
}
